package handlers

import (
	"errors"
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"swu.com/80p/internal/dbs"
)

// 更新行接口的 Gin Handler
func UpdateHandler(c *gin.Context) {
	tableName := c.Param("tableName")
	id := c.Param("id")
	primaryKeyName := getPrimayKey(c.Query("primaryKeyName"))

	var data map[string]interface{}
	if err := c.ShouldBindJSON(&data); err != nil {
		c.JSON(http.StatusBadRequest, getGinError(err))
		return
	}

	if len(data) == 0 {
		c.JSON(http.StatusBadRequest, getGinError(errors.New("no data provided for update")))
		return
	}

	result := dbs.GetDB().Table(tableName).Where(primaryKeyName+" = ?", id).Updates(data)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, getGinError(fmt.Errorf("database error: %v", result.Error)))
		return
	}

	c.JSON(http.StatusOK, getGinResult(gin.H{"updated": result.RowsAffected}))
}
